import { defineStore } from "pinia";
import { IShowTab } from "@renderer/store/pinia/type";
import { postRequest } from "@renderer/api/request";
import API from "@renderer/api/api";
import { useUserOpStore } from "@renderer/store/pinia/userOp";
import { router } from "@renderer/router/router";
import { useDicomDataStore } from "@renderer/store/pinia/dicomData";
import { EnumViewMode, EnumViewType } from "@renderer/assets/types";
import { useViewManagerStore } from "@renderer/store/pinia/viewManager";
import { idHelper } from "@renderer/store/pinia/helper";

const useTabManagerStore = defineStore("tabManager", {
  state: () => {
    return {
      tabRecords: {} as Record<string, IShowTab>,
      activeTabId: "" as string,
    };
  },
  getters: {
    activeDicomInfo: (state: any) => {
      if (state.activeTabId !== "") {
        return {
          seriesId: state.tabRecords[state.activeTabId].seriesId,
          patientUID: state.tabRecords[state.activeTabId].extends.patientUID,
          seriesDesc: state.tabRecords[state.activeTabId].extends.desc,
          patientName: state.tabRecords[state.activeTabId].extends.patientName,
        };
      } else {
        return null;
      }
    },
    allTabIds: (state) => {
      return Object.keys(state.tabRecords);
    },
  },
  actions: {
    clearActiveTab() {
      this.activeTabId = "";
    },
    selectViewType(viewMode: EnumViewMode, viewType: EnumViewType) {
      const dicomStore = useDicomDataStore();
      if (dicomStore.selectedSeriesUIDArr.length !== 1) {
        return;
      }
      const seriesUID = dicomStore.selectedSeriesUIDArr[0];
      const { patientUID, seriesId } = dicomStore.parseSeriesUID(seriesUID);
      const newTabId = idHelper.generateNewTabId({
        viewMode,
        tabType: viewMode,
        patientUID,
        seriesId,
        viewType,
      });
      this.appendNewTabRecord(newTabId);
    },
    setActiveTabId(activeTabId: string): void {
      this.activeTabId = activeTabId;
      const { tabType } = idHelper.resolveTabId(activeTabId);
      const opStore = useUserOpStore();
      const dicomStore = useDicomDataStore();
      switch (tabType) {
        case EnumViewMode.quick:
          dicomStore.updateSelectedSeriesUIDByActiveTab(activeTabId);
          router.push(`/${EnumViewMode.quick}/${activeTabId}`);
          opStore.addNewViewOpObjByTabId(activeTabId);

          break;

        case EnumViewMode.normal:
          dicomStore.updateSelectedSeriesUIDByActiveTab(activeTabId);
          router.push(`/${EnumViewMode.normal}/${activeTabId}`);
          opStore.addGroupNewViewOpObjByTabId(activeTabId);
          break;
        case EnumViewType.threeD:
          dicomStore.updateSelectedSeriesUIDByActiveTab(activeTabId);
          router.push(`/${EnumViewType.threeD}/${activeTabId}`);
          opStore.addNewViewOpObjByTabId(activeTabId);
          break;
        case "setting":
          router.push(`/setting`);
          break;
        case "tag":
          dicomStore.updateSelectedSeriesUIDByActiveTab(activeTabId);
          router.push(`/tag/${activeTabId}`);
          break;
        default:
          break;
      }

    },
    appendNewTabRecord(newTabId: string): void {
      if (this.allTabIds.includes(newTabId)) {
        this.setActiveTabId(newTabId);
        return;
      }
      const dicomStore = useDicomDataStore();
      let seriesInfo: any;
      const viewStore = useViewManagerStore();
      let subViewIds: any;
      const { tabType, patientUID, seriesId, viewMode} = idHelper.resolveTabId(newTabId);
      let tabLabel: string;
      switch (tabType) {
        case "setting":
          tabLabel = tabType;
          this.tabRecords[newTabId] = {
            tabLabel,
            tabId: newTabId,
            seriesId,
            tabType,
          };
          this.setActiveTabId(newTabId);
          break;
        case 'tag':
          break;

        case 'quick':
          seriesInfo = dicomStore.seriesRecord[seriesId];
          tabLabel = `${seriesInfo.patientName} - ${seriesInfo.desc ? seriesInfo.desc : "无描述"}`;
          this.tabRecords[newTabId] = {
            tabLabel,
            tabId: newTabId,
            seriesId,
            tabType,
            extends: seriesInfo,
          };
          subViewIds = viewStore.createWaitingToggleSubView({
            patientUID,
            seriesId,
            viewMode,
            viewTypeArr: [EnumViewType.stack, EnumViewType.ax, EnumViewType.sag, EnumViewType.cor],
            tabId:newTabId,
            groupId: newTabId,
          });
          this.startLoadSeries({
            groupId: newTabId,
            subViewIds,
            seriesId
          });

          this.setActiveTabId(newTabId);
          break;

        case 'normal':
          seriesInfo = dicomStore.seriesRecord[seriesId];
          tabLabel = `${seriesInfo.patientName} - ${seriesInfo.desc ? seriesInfo.desc : "无描述"}`;
          this.tabRecords[newTabId] = {
            tabLabel,
            tabId: newTabId,
            seriesId,
            tabType,
            extends: seriesInfo,
          };
          subViewIds = viewStore.batchCreateNormalMprView({
            patientUID,
            seriesId,
            viewMode,
            tabId:newTabId,
            groupId: newTabId
          });
          this.startLoadSeries({
            groupId: newTabId,
            subViewIds,
            seriesId
          });
          this.setActiveTabId(newTabId);
          break;
        default:
      }
    },
    startLoadSeries({
      groupId,
      subViewIds,
                      seriesId
                    }) {
        postRequest(API.loadSeries, {
          groupId,
          subViewIds,
          seriesId,
        });
    },
    /*
     * 关闭显示影像series的tab。
     * */
    removeTabById(tabId: string) {
      const opStore = useUserOpStore();
      opStore.removeViewOpByTab(tabId);
      delete this.tabRecords[tabId];
      const keys = Array.from(Object.keys(this.tabRecords));
      if (keys.length >= 1) {
        const nextActiveKey = keys[keys.length - 1];
        this.setActiveTabId(nextActiveKey);
      } else {
        this.clearActiveTab();
        router.push("/");
      }
    },
  },
});

export { useTabManagerStore };
